//
//  DXOAuthViewController.swift
//  新浪微博
//
//  Created by dix on 2017/1/18.
//  Copyright © 2017年 dix. All rights reserved.
//

import UIKit
import YYModel
class DXOAuthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
    }
    override func loadView() {
        view = webView
        let urlstr = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)"
        //实例化
        let url = URL(string: urlstr)
        guard let u = url else {
            return
        }
        //实例化
        let request = URLRequest(url: u)
        //加载
        webView.loadRequest(request)
        
    }
   private func setUpUI(){
        setUpNAV()
    }
    
    func setUpNAV(){
        title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", targrt: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: nil, title: "自动填充", targrt: self, action: #selector(autofillClick))
    }
    
    


    //MARK: - 懒加载控件
    fileprivate lazy var webView : UIWebView = {
        let view = UIWebView()
        //设置代理
        view.delegate = self
        return view
    
    }()
    
}

extension DXOAuthViewController:UIWebViewDelegate{
    ///开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
    }
    //webView 将要加载的请求 会走该方法 默认返回true 允许加载将要加载的请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //将要加载请求的字符串
        let urlStr = request.url?.absoluteString
        //判断urlStr 是否为nil 且字符串的前缀是回调页
        if let u = urlStr,u.hasPrefix(REDIRECT_URI) {
            // 请求参数部分url?.query
            let query = request.url?.query
            //判断query 是否为nil
            if let q = query {
                //截取code
                let code = q.substring(from: "code=".endIndex)
                
                DXOAuthViewModel.shared.getUserAccount(code: code, isFinish: { (isFinish) in
                    if !isFinish {
                        print("失败")
                        return
                    }else{
                        print("成功")
                        //先关闭当前控制器在发送通知
                        self.dismiss(animated: false, completion: { 
                            //发送通知
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: SWITCHROOTVIEWCONTROLLERNOTI), object: nil)
                        })
                    }
                })
                return false
            }
        }
        return true
    }

}

//MARK: - 监听事件
extension DXOAuthViewController {
    @objc fileprivate func cancelClick(){
        dismiss(animated: true, completion: nil)
        
    }
    @objc fileprivate func autofillClick(){
        print("自动填充点击")
        //js
        let jsString = "document.getElementById('userId').value='\(DXWBNAME)';document.getElementById('passwd').value='\(DXWBPASSWD)';"
        //js注入
        webView.stringByEvaluatingJavaScript(from: jsString)
    
    }
    
    
}

